package com.blc.util;

import lombok.Getter;
import lombok.SneakyThrows;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author tidudada
 * @Description  get和post的请求交互
 * @Date 上午11:01 2021/11/24
 **/
@Getter
public class InteractionUtil {
    private Boolean postBool;
    private Boolean getBool;

    // post
    @SneakyThrows
    public String sendPost(String url, String body){
        boolean flag =false;
        URL postUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        //如果想要输出数据就需要设为true 主要是post请求
        connection.setDoOutput(true);
        connection.setDoInput(true); // 这样也需要为true 默认就是true
        OutputStream outputStream = connection.getOutputStream();
        // 写数据
        outputStream.write(body.getBytes());
        outputStream.close();
        InputStream inputStream = connection.getInputStream();
        // 获取响应
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder builder = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1){
            builder.append(new String(bytes,0,len));
        }
        String message = builder.toString();
        System.out.println(message);
        if (!message.contains("errcode")){
            flag = true;
        }
        this.postBool = flag;
        return message;
    }

    // 发送get请求
    @SneakyThrows
    public String sendGet(String url) {
        String tokenMess;
        HttpURLConnection httpURLConnection;
        InputStream inputStream = null;
        try {
            URL httpUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            if (httpURLConnection.getResponseCode() != 200) {
                this.getBool = false;
            }
            inputStream = httpURLConnection.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder buffer = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                buffer.append(new java.lang.String(bytes, 0, len));
            }
            tokenMess = buffer.toString();
        } finally {
            assert inputStream != null;
            inputStream.close();
        }
        return tokenMess;
    }






}
